#include "stdafx.h"
#include "FixCircleDequeue.h"
#include <memory>
#include <iostream>
#include "MemoryPool.h"
#include "DataDefinition.h"

FixCircleDequeue::FixCircleDequeue(unsigned int p_uiEntireBufferSize,unsigned int p_uiElementAmount, unsigned int p_uiElementSize,unsigned int p_uiBeginSequence,unsigned int p_uiEndSequence,unsigned char p_uiEntireDataType, unsigned char p_uiIncrementDataType)
	:CircleDequeueBase(p_uiEntireBufferSize,p_uiElementAmount, p_uiElementSize, p_uiBeginSequence, p_uiEndSequence, p_uiEntireDataType, p_uiIncrementDataType)
{
}

bool FixCircleDequeue::WriteData(char* p_szBuffer, unsigned int p_uiBufferSize)
{
	EnterCriticalSection(&m_csLock);
	// Store current local date
	DateTime clsLocalDate;
	clsLocalDate.SetToCurrentDate();
	m_clsLastDate = clsLocalDate;

	DataHead* pstDataHead = (DataHead*)m_pszSendBuffer;
	pstDataHead->m_ucDataType = m_ucEntireDataType;
	pstDataHead->m_uiDataLength = p_uiBufferSize;
	memcpy(m_pszSendBuffer + sizeof(DataHead),p_szBuffer,p_uiBufferSize);
	m_uiSendBufferLength = p_uiBufferSize + sizeof(DataHead);
	memcpy(m_pszEntireBuffer,p_szBuffer,p_uiBufferSize);
	m_uiEntireBufferLength = p_uiBufferSize;

	if(false == m_vecRookieSocketList.empty())
	{
		if(false == CircleDequeueBase::Notify(m_vecRookieSocketList,m_pszSendBuffer,m_uiSendBufferLength))
		{
			LeaveCriticalSection(&m_csLock);
			return false;
		}
	}
	if(false == m_vecAlivedSocketList.empty())
	{
		if(false == CircleDequeueBase::Notify(m_vecAlivedSocketList,m_pszSendBuffer,m_uiSendBufferLength))
		{
			LeaveCriticalSection(&m_csLock);
			return false;
		}
	}

	m_uiSendBufferIndex++;
	m_vecAlivedSocketList.insert(m_vecAlivedSocketList.end(),m_vecRookieSocketList.begin(),m_vecRookieSocketList.end());
	m_vecRookieSocketList.clear();

	LeaveCriticalSection(&m_csLock);
	return true;
}

bool FixCircleDequeue::WriteData(char* p_szBufferAddress, unsigned int p_uiBufferSize, unsigned char p_cType, bool p_bIsResend)
{
	EnterCriticalSection(&m_csLock);
	// Store current local date
	DateTime clsLocalDate;
	clsLocalDate.SetToCurrentDate();
	m_clsLastDate = clsLocalDate;

	LeaveCriticalSection(&m_csLock);
	return true;
}